/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component} from 'react';
import {Form, Input, Radio, Select, Checkbox, TreeSelect, Drawer, Button, Modal,message,Tooltip} from 'antd';
import {connect} from 'dva';
import request from '@/utils/request';
import {renderTreeNodes,afterCloseModal} from '@/utils/utils';
import BuildModalTitle from '@/components/BuildModalTitle';
import type2 from './../../images/type2.jpg';
import type3 from './../../images/type3.jpg';
import type6 from './../../images/type6.jpg';
import AddOrEditNode from './addOrEditNode'
import debounce from "lodash/debounce";
const CheckboxGroup = Checkbox.Group;
const FormItem = Form.Item;
const TreeNode = TreeSelect.TreeNode;
const Option = Select.Option;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      villages: [],
      editRecord: {},
      nodeDataArray: [],
      linkDataArray: [],
      modify: false,
      exitJson:{},
      linkType:1
    };
  }

  componentDidMount() {
    const that = this;
    let nodeDataArray = []
    let linkDataArray = []
    if (this.props.editRecord.graph) {
      nodeDataArray = this.props.editRecord.graph.vertexs
      // for (let i = 0; i < nodeDataArray.length; i++) {
      //   let source='';
      //   if(nodeDataArray[i].type === 1){
      //     source='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg1.qjy168.com%2Fprovide%2F2013%2F03%2F14%2F4398222_20130314092128.JPG&refer=http%3A%2F%2Fimg1.qjy168.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg';
      //
      //   }else if(nodeDataArray[i].type === 2){
      //
      //   }
      //   nodeDataArray[i].source = nodeDataArray[i].type === 1 ? 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg1.qjy168.com%2Fprovide%2F2013%2F03%2F14%2F4398222_20130314092128.JPG&refer=http%3A%2F%2Fimg1.qjy168.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg'
      //     : 'https://img2.baidu.com/it/u=2879511838,1938169181&fm=26&fmt=auto&gp=0.jpg'
      //
      // }
      linkDataArray = this.props.editRecord.graph.edges;
      this.setState({
        linkDataArray, nodeDataArray
      }, function () {
        that.renderGraph();
      })

    } else {
      that.renderGraph();
    }


  }
  componentWillUnmount() {
    const that = this;
    if(this.myDiagram){
      this.myDiagram=null
    }

    if(this.myPalette){
      this.myPalette=null
    }
  }
  renderGraph = () => {
    const {
      nodeDataArray, linkDataArray
    } = this.state;
    const that = this;
    const $ = window.$;
    const go = window.go
    if(! this.myDiagram){
      that.myDiagram =
        $(go.Diagram, 'myDiagramDiv',
          {
            'toolManager.mouseWheelBehavior': go.ToolManager.WheelZoom,
            'undoManager.isEnabled': true, // enable Ctrl-Z to undo and Ctrl-Y to redo
            'LinkDrawn': showLinkLabel,  //画线
            'toolManager.hoverDelay': 300,
          });
    }


    that.myDiagram.addDiagramListener("Modified", function (e) {
      // that.setState({
      //     hadEdit:true
      // })
      console.log('modify')
      that.setState({
        modify: true,
      })
    });

    function showLinkLabel(e) {
      console.log('e', e);
      var label = e.subject.findObject('LABEL');
      console.log('label', label);
      if (label !== null) label.visible = false;//如果figure=Diamond则线的文字可以编辑
    }
    that.myDiagram.addDiagramListener("LinkDrawn", function(e,obj){
      console.log('连线时间')
      console.log('clickLine e',e.subject)
      console.log('(e.subject.data ) ',(e.subject.data ) )
      let data=e.subject.data;
      let m=e.subject
      if(that.state.linkType===1){
        that.myDiagram.model.setDataProperty(
          e.subject.data,
          "color",
          '#777'
        );
      }else if(that.state.linkType===-1){
        that.myDiagram.model.setDataProperty(
          e.subject.data,
          "color",
          'blue'
        );
      }else{
        that.myDiagram.model.setDataProperty(
          e.subject.data,
          "color",
          'blue'
        );
      }

    });
    that.myDiagram.grid = $(go.Panel, 'Grid',
      $(go.Shape, 'LineH', {stroke: 'gray', strokeWidth: 0.5}),
      $(go.Shape, 'LineH', {stroke: 'darkslategray', strokeWidth: 1.5, interval: 10}),
      $(go.Shape, 'LineV', {stroke: 'gray', strokeWidth: 0.5}),
      $(go.Shape, 'LineV', {stroke: 'darkslategray', strokeWidth: 1.5, interval: 10}),
    );
    that.myDiagram.toolManager.draggingTool.isGridSnapEnabled = true;
    that.myDiagram.undoManager.isEnabled = true;
    // define a simple Node template
    that.myDiagram.nodeTemplate =
      $(go.Node, 'Auto',
        new go.Binding('location', 'loc', go.Point.parse).makeTwoWay(go.Point.stringify),
        // the entire node will have a light-blue background
        {
          // the Node.location is at the center of each node
          locationSpot: go.Spot.Center,
          mouseEnter: function (e, obj) {
            showPorts(obj.part, true);
          },
          mouseLeave: function (e, obj) {
            showPorts(obj.part, false);
          },
        },
        {background: '#44CCFF'},
        new go.Binding("background", "analyze_consumption", function (v) {
          if (v == -1) {
            return '#44CCFF'
          } else {
            return '#48d304'
          }
        }),
        $(go.Panel, 'Horizontal',
          $(go.Picture,
            // Pictures should normally have an explicit width and height.
            // that picture has a red background, only visible when there is no source set
            // or when the image is partially transparent.
            {width: 60, height: 60, background: 'red'},
            // Picture.source is data bound to the "source" attribute of the model data
            new go.Binding('source')),
          $(go.Panel, 'Vertical',
            $(go.TextBlock,
              'Default Text',  // the initial value for TextBlock.text
              // some room around the text, a larger font, and a white stroke:
              {
                margin: 5, height: 18, stroke: 'white', font: 'bold 16px sans-serif',
                verticalAlignment: go.Spot.Center, editable: false,
              },
              // TextBlock.text is data bound to the "name" attribute of the model data
              new go.Binding('text', 'name')),
            $('Button',
              {
                margin: 2,
                click: incrementCounter,
              },
              $(go.TextBlock, '更改节点')),
          ),
        ),
        makePort('T', go.Spot.Top, true, true),//创建点，顶点不可输出，可以输入
        makePort('L', go.Spot.Left, true, true),
        makePort('R', go.Spot.Right, true, true),
        makePort('B', go.Spot.Bottom, true, true),
        // {
        //     toolTip:                       // define a tooltip for each node
        //         $(go.Adornment, "Spot",      // that has several labels around it
        //             { background: "transparent" },  // avoid hiding tooltip when mouse moves
        //             $(go.Placeholder, { padding: 5 }),
        //             $(go.TextBlock,
        //                 { alignment: go.Spot.Top, alignmentFocus: go.Spot.Bottom, stroke: "red" , font: "bold 16px sans-serif",
        //                   },
        //                 new go.Binding("text", "key", function(s) { return "key: " + s; })),
        //             $(go.TextBlock, "Bottom",
        //                 { alignment: go.Spot.Bottom, alignmentFocus: go.Spot.Top, stroke: "red" , font: "bold 16px sans-serif"},
        //                 new go.Binding("text", "color", function(s) { return "color: " + s; }))
        //         )  // end Adornment
        // }
      );

    function incrementCounter(e, obj) {
      console.log('e', e)
      console.log('obj', obj.diagram.div.id)
      var node = obj.part;
      var data = node.data;
      console.log('data', data);
      if (data) {
        if (obj.diagram.div.id === 'myPaletteDiv') {
          return
        }
        node.diagram.model.commit(function (m) {
          that.setState({
            exitJson: that.getJson(),
            editRecord: data,
            editModal: true,
            graphModel: m
          });
          // m.set(data, 'name', '123');
        }, 'clicked');
      }
    }

    function showPorts(node, show) {
      var diagram = node.diagram;
      if (!diagram || diagram.isReadOnly || !diagram.allowLink) return;
      node.ports.each(function (port) {
        port.stroke = (show ? 'black' : null);
      });
    }

    function makePort(name, spot, output, input) {
      // the port is basically just a small circle that has a white stroke when it is made visible
      return $(go.Shape, 'Circle',
        {
          fill: 'transparent',
          stroke: null,  // that is changed to "white" in the showPorts function
          desiredSize: new go.Size(8, 8),
          alignment: spot, alignmentFocus: spot,  // align the port on the main Shape
          portId: name,  //点属性的描述 declare that object to be a "port"
          fromSpot: spot, toSpot: spot,  // declare where links may connect at that port
          fromLinkable: output, toLinkable: input,  //输入和输出 declare whether the user may draw links to/from here
          cursor: 'pointer',  // show a different cursor to indicate potential link point
        });
    }
    function clickLine(e,obj){
      console.log('clickLine e',e)
      console.log('clickLine obj',obj)
      console.log('clickLine node',obj.part)
      var node = obj.part;
      var data = node.data;
      node.diagram.model.commit(function (m) {
        console.log(m)
        console.log(data.color)
        let color =data.color
        if(that.state.linkType===1){
          m.set(data, 'color', '#777');
        }else if(that.state.linkType===-1){
          m.set(data, 'color', 'blue');
        }else{
          m.set(data, 'color', 'blue');
        }

      }, 'clicked');
    }

    //固定的线
    that.myDiagram.linkTemplate =
      $(go.Link,
        $(go.Shape,
          new go.Binding('stroke', 'color',function (params){
            if(params){
              return params
            }else{
              return 'blue'
            }
          }),
          {toArrow: "OpenTriangle", fill: null, strokeWidth: 6,
            click:clickLine},
        ),  // shape.strokeWidth = data.thick
        $(go.Shape, new go.Binding('stroke', 'color',function (params){
          if(params){
            return params
          }else{
            return 'blue'
          }
        }),{isPanelMain: true, strokeWidth: 6,   click:clickLine}),

        // $(go.Shape, { isPanelMain: true, stroke: "lightblue", strokeWidth: 8, name: "PIPE", strokeDashArray: [8, 70] }),
        $(go.Panel, "Auto",  // that whole Panel is a link label
          {visible: false, name: "LABEL", segmentIndex: 2, segmentFraction: 0.5},
          $(go.Shape, {fill: "yellow", stroke: "gray"}),
          $(go.TextBlock, {margin: 3, font: "bold 16px sans-serif",editable:true},
            new go.Binding("text", "from"))
        )
      );


    var model = $(go.GraphLinksModel);
    model.nodeDataArray = nodeDataArray;
    model.linkDataArray = linkDataArray;
    that.myDiagram.model = model;
    that.myDiagram.commandHandler.zoomToFit();
    // Animate the flow in the pipes
    var animation = new go.Animation();
    animation.easing = go.Animation.EaseLinear;
    that.myDiagram.links.each(function (link) {
      animation.add(link.findObject('PIPE'), 'strokeDashOffset', 20, 0);
    });
    // Run indefinitely
    animation.runCount = Infinity;
    animation.start();

    //初始化左边操作框的图像
    if(!this.myPalette){
      this.myPalette =
        $(go.Palette, 'myPaletteDiv',  // must name or refer to the DIV HTML element
          {
            'animationManager.duration': 800, // slightly longer than default (600ms) animation
            nodeTemplateMap: that.myDiagram.nodeTemplateMap,  // 使用this.myDiagram.nodeTemplateMap来定义图形 share the templates used by this.myDiagram
            /**
             * model根据category来识别定义的图形
             * 当没有category时使用 this.myDiagram.nodeTemplateMap.add("")定义的图形
             * */
            model: new go.GraphLinksModel([  //定义图形 specify the contents of the Palette
              {
                name: '普通水表',
                type: 1,
                analyze_consumption: -1,
                source: 'http://106.12.97.66:4370/meter.jpg',
              },
              {
                name: '水表群组',
                type: 6,
                analyze_consumption: -1,
                source: type6,
              },
              {
                name: '虚拟水表',
                type: 2,
                analyze_consumption: -1,
                source: type2,
              },
              {
                name: '虚拟水表',
                type: 3,
                analyze_consumption: -1,
                source: type3,
              },
              {
                name: '工作站点',
                type: 4,
                analyze_consumption: -1,
                source: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fgss0.baidu.com%2F-4o3dSag_xI4khGko9WTAnF6hhy%2Fzhidao%2Fpic%2Fitem%2Fa08b87d6277f9e2f5b659a731630e924b899f37d.jpg&refer=http%3A%2F%2Fgss0.baidu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1672990929&t=7623561f3ef0c600d4497bdcc52e16da',
              },
              {
                name: '下级DMA分区',
                type: 5,
                analyze_consumption: -1,
                source: "https://img1.baidu.com/it/u=1920648721,3866137353&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=553",
              },
            ]),
          });
    }



    function save() {
      document.getElementById('mySavedModel').value = this.myDiagram.model.toJson();
      this.myDiagram.isModified = false;
    }

  };
  getJson = () => {
    console.log( this.myDiagram.model)
    const tojson = this.myDiagram.model.toJson();
    return JSON.parse(tojson);
  };
  saveGraph=()=>{
    const getJson = this.getJson();
    console.log('getJson', getJson);
    const that = this;
    for(let i=0;i<getJson.nodeDataArray.length;i++){
      if(typeof(getJson.nodeDataArray[i].key)!=='string'){
        console.log(getJson.nodeDataArray[i])
        message.error(`节点‘${getJson.nodeDataArray[i].name}’错误,请不要使用默认名称,请检查`)
        return false
      }
    }
    for(let i=0;i<getJson.linkDataArray.length;i++){
      if(getJson.linkDataArray[i].color==='#777'){
        getJson.linkDataArray[i].type=1
      }else if(getJson.linkDataArray[i].color==='blue'){
        getJson.linkDataArray[i].type=2
      }else{
        getJson.linkDataArray[i].type=1
      }
    }

    request(`/areas/${this.props.editRecord.id}/graph`, {
      method: 'PUT',
      data:{
        graph:{
          vertexs: getJson.nodeDataArray,
          edges: getJson.linkDataArray,
        }
      }
    }).then((response) => {
      if (response.status === 200) {
        message.success('修改水表关系成功');
        that.props.handleSearch()
        that.props.onClose()
      }
    });
    return
    this.props.dispatch({
      type: `meters_graph/edit`,
      payload: {
        id: data.id,
        name: data.name,
        vertexs: getJson.nodeDataArray,
        edges: getJson.linkDataArray,
      },
      callback() {
        message.success('修改水表关系成功');
        that.myDiagram.isModified = false;
        that.props.dispatch({
          type: `meters_graph/changeOneState`,
          payload: {
            modify:false,
          },
        })
      },
    });
  }
  handleEditWorkstation=(key,name,sort)=>{
    this.state.graphModel.set(this.state.editRecord, 'key', key)
    this.state.graphModel.set(this.state.editRecord, 'name',name)
    this.state.graphModel.set(this.state.editRecord, 'sort', Number(sort))
    this.myDiagram.isModified = true;
    this.setState({
      editModal:false
    })
  }
  handleEdit=()=>{
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues',formValues)
    const state = this.EditForm.state;

    if(this.state.graphModel){
      if(this.state.editRecord.type===2||this.state.editRecord.type===3){
        this.state.graphModel.set(this.state.editRecord, 'key', formValues.name)
        this.state.graphModel.set(this.state.editRecord, 'name', formValues.name)
        this.state.graphModel.set(this.state.editRecord, 'sort', Number(formValues.sort))
      }else if(this.state.editRecord.type===4){
        return;
        if(!formValues.workstation.key){
          message.error('请选择一个工作站点')
          return
        }
        this.state.graphModel.set(this.state.editRecord, 'key', formValues.workstation.key)
        this.state.graphModel.set(this.state.editRecord, 'name', formValues.workstation.label)
        this.state.graphModel.set(this.state.editRecord, 'sort', Number(formValues.sort))

      }else if(this.state.editRecord.type===5){
        if(!formValues.dma.value){
          message.error('请选择一个DMA分区')
          return
        }
        this.state.graphModel.set(this.state.editRecord, 'key', formValues.dma.value)
        this.state.graphModel.set(this.state.editRecord, 'name', formValues.dma.label)
        this.state.graphModel.set(this.state.editRecord, 'sort',  Number(formValues.sort))

      }else if(this.state.editRecord.type===6){
        console.log('state',state)
        if(!formValues.name){
          message.error('请输入群组名称')
          return
        }
        if(state.selected_data.length===0){
          message.error('右边表格至少需要一个水表')
          return
        }
        this.state.graphModel.set(this.state.editRecord, 'key', formValues.name)
        this.state.graphModel.set(this.state.editRecord, 'name', formValues.name)
        this.state.graphModel.set(this.state.editRecord, 'sort',  Number(formValues.sort))
        let sub_vertexs=[]
        for(let i=0;i<state.selected_data.length;i++){
          sub_vertexs.push({
            "key": state.selected_data[i].id,
            "name": state.selected_data[i].address,
            "address": state.selected_data[i].address,
            "number": state.selected_data[i].number,
            "sort": 999,
            "type": 1
          })
        }
        this.state.graphModel.set(this.state.editRecord, 'sub_vertexs',sub_vertexs)
      }else if(this.state.editRecord.type===1){
        return;
      }else{
        if(!formValues.meter){
          message.error('请选择一个水表')
          return
        }
        this.state.graphModel.set(this.state.editRecord, 'key', formValues.meter.key)
        this.state.graphModel.set(this.state.editRecord, 'name', formValues.meter.label)
        this.state.graphModel.set(this.state.editRecord, 'sort',  Number(formValues.sort))

      }
      this.myDiagram.isModified = true;
      this.setState({
        editModal:false
      })
    }

  }
  changeType=(e)=>{
      this.setState({
        linkType: e.target.value,
      },function (){
      })

  }
  render() {
    const that = this;
    const {
      graph
    } = this.props;

    return <div style={{
      height: '100%',
      width: '100%',
      overflow: 'hidden',
    }}>
      <div style={{textAlign:'center',marginBottom:'10px'}}>
        <Radio.Group value={this.state.linkType} buttonStyle="solid"  onChange ={this.changeType }>
          <Tooltip title="计算漏损率">
          <Radio.Button value={1}>灰色线</Radio.Button>
          </Tooltip>
          <Tooltip title="不计算漏损率">
          <Radio.Button value={-1}>蓝色线</Radio.Button>
          </Tooltip>
        </Radio.Group>
      </div>

      <div id={'grapDiv'} style={{
        display: 'flex',
        height: '80vh',

        background: '#000',
        postion: 'relative',
      }}>
        <div id="myPaletteDiv" style={{width: '200px', height: '100%', paddingTop: '15px'}}>

        </div>
        <div id="myDiagramDiv" style={{flex: 1, backgroundColor: '#DAE4E4'}}>

        </div>
        <div style={{
          color: '#fff',
          padding: '10px',
          fontSize: '16px',
          width: '200px',
          position: 'absolute',
          left: '0',
          bottom: '56px'
        }}>
          <p style={{textIndent: '2em', marginBottom: '6px'}}>请不要出现"环形"或者"重复"连线。</p>

        </div>
      </div>
      <div
        style={{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
        }}
      >
        <Button onClick={this.props.cancel} style={{marginRight: 8}}>
          取消
        </Button>
        <Button onClick={this.saveGraph} type="primary">
          确定
        </Button>
      </div>
      <Drawer
        title={`${this.state.editRecord.number} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={800}
        visible={this.state.infoModal}
      >
      </Drawer>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`更改节点`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        keyboard={false}
        onOk={this.handleEdit}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({editModal: false, editRecord: {}});
        }}
        width={this.state.editRecord.type===6?'100vw':650}


      >
        <AddOrEditNode
          handleEditWorkstation={this.handleEditWorkstation}
          exitJson={this.state.exitJson}
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}/>
      </Modal>
    </div>;
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


